import Vue from "vue";
import BaseDialog from "@/components/dialog/BaseDialog.vue";

function getDialogConstructor(ctxCpm, dlgProps, afterSubmitHandler, onCancelClick) {
	return Vue.extend({
		render(h) {
			return h(
				BaseDialog, {
					props: {
						...dlgProps,
						async handleOk(slot, closeFun) {
							// 调用自定义的表单组件中的 formSubmit 方法, 方法名称必须是formSubmit
							await slot.componentInstance.formSubmit();
							closeFun();
							if (afterSubmitHandler) {
								await afterSubmitHandler();
							}
						},
						handleCancel: onCancelClick
					}
				},
				[h(ctxCpm, {
					slot: 'content',
					props: {
						formProps: dlgProps.formProps
					}
				},)]
			)
		}
	})
}

export const useDialog = (ctxCpm, dlgProps, onOkClick, onCancelClick) => {
	let DialogConstructor = getDialogConstructor(ctxCpm, dlgProps, onOkClick, onCancelClick);
	const dlg = new DialogConstructor();
	const div = document.createElement("div");
	document.body.appendChild(div);
	const dlgInstance = dlg.$mount(div);
	return () => {
		dlgInstance.$el.remove();
		dlgInstance.$destroy();
	}
}